/*
 * @lc app=leetcode.cn id=20 lang=typescript
 *
 * [20] 有效的括号
 */

// @lc code=start
function isValid(s: string): boolean {
    let count = {
        "[": 3,
        "(": 2,
        "{": 1,
        "}": -1,
        ")": -2,
        "]": -3,
    };
    let stack: number[] = [];
    for (let i of s.split("")) {
        const c = count[i];
        if (stack.length == 0) {
            if (c < 0) return false;
            stack.push(c);
            continue;
        }
        const final = stack[stack.length - 1];
        if (c > 0) {
            stack.push(c);
        } else if (final == -c) {
            stack.pop();
        } else {
            return false;
        }
    }
    return !stack.length;
}
// @lc code=end
